from nicegui import ui
import pandas as pd
import plotly.express as px

# 载入数据
df = pd.read_csv('cleaned_personality_data.csv', header=None)

# 给列命名
df.columns = ['Value', 'Alone', 'Duration', 'Score', 'Participate', 'Interest', 'Time', 'Personality']

# 定义颜色映射
color_map = {'Introvert': 'blue', 'Extrovert': 'orange'}

# UI布局
with ui.row().classes('p-4'):
    # 左侧筛选面板
    with ui.column().classes('w-1/4'):
        ui.label('筛选条件').classes('text-xl font-bold mb-2')

        # 性格类型筛选
        personality_select = ui.select(
            label='性格类型',
            options=['All'] + df['Personality'].unique().tolist(),
            value='All'
        )

        # 应用按钮
        def update():
            filtered = df if personality_select.value == 'All' else df[df['Personality'] == personality_select.value]
            update_charts(filtered)

        ui.button('应用筛选', on_click=update).classes('mt-2')

    # 右侧图表区
    with ui.column().classes('w-3/4'):
        # 初始3D散点图
        scatter3d_fig = px.scatter_3d(
            df,
            x='Value',
            y='Duration',
            z='Score',
            color='Personality',
            color_discrete_map=color_map,
            title='性格分析3D散点图'
        )
        scatter3d_chart = ui.plotly(scatter3d_fig).style('height: 600px')

# 更新图表函数
def update_charts(filtered_df):
    scatter3d_fig = px.scatter_3d(
        filtered_df,
        x='Value',
        y='Duration',
        z='Score',
        color='Personality',
        color_discrete_map=color_map,
        title='性格分析3D散点图'
    )
    scatter3d_chart.update_figure(scatter3d_fig)

# 兼容多进程的主程序保护
# if __name__ in {"__main__", "__mp_main__"}:
#     ui.run()
if __name__ in {"__main__", "__mp_main__"}:
    import sys
    port = 8084
    if '--port' in sys.argv:
        port_index = sys.argv.index('--port')
        if port_index + 1 < len(sys.argv):
            port = int(sys.argv[port_index + 1])
    ui.run(title='详细数据分析', port=port, show=True)